<?php
class Model_User
{
    static private $_table = 'user';
    
    public static function add($userName, $levelID)
    {
        $userName = trim($userName, "\r\n\t ");
        if(!Model_Validator::userName($userName)){
            throw new Eren_Exception('用户名不合法，请填写正确的用户名，只能是字母、空格和数字(1-50)', -1);
        }
        if(self::ifUserNameExist($userName)){
            throw new Eren_Exception('用户名已经存在，请更换后重试', -1);
        }
        if(!Model_Validator::level($levelID)){
            throw new Eren_Exception('角色异常，请重新选择', -1);
        }
        
        $fields = array(
        'username'       => $userName,
        'password'       => Model_Common::MD5Hash($userName),
        'levelid'        => $levelID,
        'createdtime'    => Model_Common::getNowTime()
        );
        $DB = Eren_Registry::get('DB');
        $id = $DB->table(self::$_table)
                 ->insert($fields);
        $log = var_export($fields, true);
        Model_Log::write("[userid:{$id}][add][{$log}]");
        return $id;
    }
    
    public static function isSignIn()
    {
        if(Eren_Registry::get('SESSION')->get('userID', '') === '')
        {
            return FALSE;
        }
        
        return TRUE;
    }
    
    public static function autoSignIn()
    {
        if(self::isSignIn()) return;
        /*$userName     = Eren_Cookie::get('userName', '');
        $password    = Eren_Cookie::get('password', '');
        if($userName && $password){
             self::signIn($userName, $password, TRUE);
        }*/
    }
    
    public static function signIn($userName, $password, $ifAuto = FALSE)
    {
        $userName = trim($userName, "\r\n\t ");
        $password = trim($password, "\r\n\t ");
        if(!$ifAuto && !Model_Validator::userName($userName)){
            throw new Eren_Exception('用户名不合法，请填写正确的用户名，只能是字母、空格和数字(1-50)', -1);
        }else if(!$ifAuto && !Model_Validator::password($password)){
            throw new Eren_Exception('密码不合法，请重新填写3位以上的密码', -1);
        }
        if(!$ifAuto) $password = Model_Common::MD5Hash($password);
        $ret = self::doSignIn($userName, $password);
        if($ret['count'] <= 0){
            self::signOut();
            if(!$ifAuto){
                throw new Eren_Exception('用户名或密码错误，请确认后重新输入', -1);
            }
        }else {
            Eren_Registry::get('SESSION')->set('userID', $ret['data'][0]['userid']);
            Eren_Registry::get('SESSION')->set('userName', $ret['data'][0]['username']);
            Eren_Registry::get('SESSION')->set('levelID', $ret['data'][0]['levelid']);
            /*Eren_Cookie::set('userName', $userName, -1);
            Eren_Cookie::set('password', $password, -1);*/
        }
        
        return true;
    }
    
    public static function doSignIn($userName, $password)
    {
        $userName = trim($userName, "\r\n\t ");
        $password = trim($password, "\r\n\t ");
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('username', '=', $userName)
                  ->wAND()
                  ->where('password', '=', $password)
                  ->select();
        return $ret;
    }
    
    public static function signOut()
    {
        Eren_Registry::get('SESSION')->delete('userID');
        Eren_Registry::get('SESSION')->delete('userName');
        Eren_Registry::get('SESSION')->delete('levelID');
        Eren_Cookie::delete('userName');
        Eren_Cookie::delete('password');
    }
    
    public static function getUserID()
    {
        return Eren_Registry::get('SESSION')->get('userID', '');
    }
    
    public static function getUserName()
    {
        return Eren_Registry::get('SESSION')->get('userName', '');
    }
    
    public static function getLevelID()
    {
        return Eren_Registry::get('SESSION')->get('levelID', '');
    }
    
    public static function getLevelName($levelID)
    {
        $levelID = intval($levelID);
        $levelInfo = Config_Default::getAuthConfig();
        return $levelInfo[$levelID]['name'];   
    }
    
    public static function getList($page)
    {
        $pagelimit = Model_Navigate::getLimit($page, Config_Default::getUserPageSize());
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '!=', Model_User::getUserID())
                  ->orderBy('userid', 'DESC')
                  ->limit($pagelimit['start'], $pagelimit['limit'])
                  ->select();
        return $ret['data'];
    }
    
    public static function getCount()
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '!=', Model_User::getUserID())
                  ->count();
        return $ret;
    }
    
    public static function ifUserIDExist($userID)
    {
        $DB = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '=', $userID)
                  ->count();
                  
        if($ret > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
   
    public static function ifUserNameExist($userName)
    {
        $userName = trim($userName, "\r\n\t ");
        $DB = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('username', '=', $userName)
                  ->count();
                  
        if($ret > 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    public static function modify($userID, $password)
    {        
        $userID = intval($userID);
        $password = trim($password, "\r\n\t ");
        if(!self::ifUserIDExist($userID)){
            throw new Eren_Exception('修改的用户不存在，请更换后重试', -1);
        }
        if(!Model_Validator::password($password)){
            throw new Eren_Exception('密码不合法，请重新填写3位以上的密码', -1);
        }
        
        $password = Model_Common::MD5Hash($password);
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '=', $userID)
                  ->update(array('password'=>$password));
        Model_Log::write("[userid:{$userID}][update]");
        return TRUE;
    }
    
    public static function delete($userID)
    {        
        $userID = intval($userID);
        if(!self::ifUserIDExist($userID)){
            throw new Eren_Exception('删除的用户不存在', -1);
        }
        
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '=', $userID)
                  ->delete();
        Model_Log::write("[userid:{$userID}][delete]");
        return TRUE;
    }
    
    public static function getById($userID)
    {
        $DB = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->where('userid', '=', $userID)
                  ->select();
        if($ret['count'] != 1){
            return false;
        }
        return $ret['data'][0];
    }
    
    public static function reset($userID)
    {        
        $userID = intval($userID);
        $userInfo = self::getById($userID);
        if(!$userInfo){
            throw new Eren_Exception('重置的用户不存在', -1);
        }
        
        self::modify($userID, $userInfo['username']);
        Model_Log::write("[userid:{$userID}][reset]");
        return TRUE;
    }
    
    public static function password($oldPassword, $newPassword, $rePassword)
    {
        $oldPassword = trim($oldPassword, "\r\n\t ");
        $newPassword = trim($newPassword, "\r\n\t ");
        $rePassword = trim($rePassword, "\r\n\t ");
        $userInfo = self::getById(self::getUserID());
        if(!$userInfo){
            throw new Eren_Exception('用户不存在', -1);
        }
        
        $oldPassword = Model_Common::MD5Hash($oldPassword);
        if($userInfo['password'] != $oldPassword){
            throw new Eren_Exception('原密码不正确', -1);
        }
        
        if($newPassword != $rePassword){
            throw new Eren_Exception('新密码和确认密码不一致，请重新输入', -1);
        }
        
        if(!Model_Validator::password($newPassword)){
            throw new Eren_Exception('新密码不合法，请重新填写3位以上的密码', -1);
        }
        
        self::modify(Model_User::getUserID(), $newPassword);
                  
        return TRUE;
    }
}